package Java基础.JUC同步工具.Semaphore;


import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 限流器底层直接使用 Semaphore，如下示例
 * Semaphore#acquire阻塞式方法。
 * @Author zhengqiang.tan
 * @Date 2021/3/26 2:15 PM
 */
public class Test {
    public static void main(String[] args) {

        ConcurrencyLimit limit = ConcurrencyLimit.create(5);
        ExecutorService executorService = Executors.newCachedThreadPool(
                new ThreadFactoryBuilder()
                        .setNameFormat("limit-%d")
                        .build());

        for (int i = 0; i < 10; i++) {
            executorService.execute(() -> {
                try {
                    limit.acquire();
                    System.out.println(Thread.currentThread().getName() + " START");
                    // 模拟内部耗时
                    TimeUnit.MILLISECONDS.sleep(new Random().nextInt(500));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    System.out.println(Thread.currentThread().getName() + " END");
                    limit.release();
                }
            });
        }
    }
}
